import React from 'react';
import { Dispatch } from 'redux';
import { connect } from 'dva';

import qs from 'qs';
import _ from 'lodash';

import { addTab, timeLimit } from '@/utils/utils';
import { Form } from '@ant-design/compatible';
import PageHeader from '@/components/PageHeader';
import { FormComponentProps } from '@ant-design/compatible/es/form';
import moment from 'moment';

import {
  Table,
  Button,
  Card,
  Col,
  Row,
  Select,
  Modal,
  Input,
  message,
  Tooltip,
  DatePicker,
  Popconfirm,
} from 'antd';

import '@ant-design/compatible/assets/index.css';

const { Item } = Form;
const { Option } = Select;
const { TextArea } = Input;
const { pathname } = window.location;
const { RangePicker } = DatePicker;

interface TableListProps extends FormComponentProps {
  dispatch: Dispatch<any>;
  logisCenterDeliveryRecoverList: any;
  INITINFO: any;
  loading: boolean;
  screen: string;
}

interface TableListState {
  current: number;
  pageSize: number | undefined;
  formValues: any;
  orderInfo: any,
  recoverDialog: boolean,
  rowId:number;
}

/* eslint react/no-multi-comp:0 */
@connect(({
  logisCenterDeliveryRecoverList,
  common: { INITINFO },
  global: { screen },
  loading,
}: any) => ({
  logisCenterDeliveryRecoverList,
  INITINFO,
  screen,
  loading: loading.effects['logisCenterDeliveryRecoverList/fetch'],
}))
class TableList extends React.Component<TableListProps, TableListState> {
  columns:any = [
    {
      title: '运单号',
      dataIndex: 'expCode',
      width: 120,
      render: (text: any) => (
        <Tooltip title={text}>
          <div
            className="wordOmit"
            style={{ maxWidth: 120 }}
          >
            {text}
          </div>
        </Tooltip>
      ),
    },
    // {
    //   title: '联系人',
    //   dataIndex: 'phone',
    //   width: 100,
    // },
    {
      title: '物流中心',
      dataIndex: 'logisName',
      width: 150,
      render: (text: any) => (
        <Tooltip title={text}>
          <div
            title={text}
            className="wordOmit"
          >
            {text || '--'}
          </div>
        </Tooltip>
      ),
    },
    {
      title: '快递公司',
      dataIndex: 'expressName',
      width: 100,
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      width: 140,
    },
    {
      title: '创建人',
      dataIndex: 'createUserName',
      width: 60,
    },
    {
      title: '原因',
      dataIndex: 'remark',
      width: 150,
      render: (text: any) => text || '--',
    },
    {
      title: '操作',
      width: 60,
      fixed: 'right',
      render: (record: any) => (
        <>
        <Popconfirm
          title="确认删除？"
          okText="确认"
          cancelText="取消"
          className="operLink"
          onConfirm={() => this.handleDel(record)}
        >
          删除
        </Popconfirm>
        </>
      ),
    },
  ];

  state: TableListState = {
    current: 1,
    pageSize: 20,
    formValues: {},
    orderInfo: {},
    recoverDialog: false,
    rowId: 0,
  };

  static getDerivedStateFromProps(props: any, state: any) {
    const { search } = props.location;
    const query = qs.parse(search, { ignoreQueryPrefix: true });
    const { page, psize, ...formValues } = query;

    return {
      ...state,
      formValues,
      current: Number(page) || 1,
      pageSize: Number(psize) || 20,
    };
  }

  componentDidMount() {
    this.setFieldsValue();
    this.fetchLogisList();
    this.fetchExpressList();
    this.fetchRecoverList();
  }

  componentDidUpdate(prevProps: any, prevState: any) {
    const { formValues, current, pageSize } = this.state;
    if (!_.isEqual(formValues, prevState.formValues)
      || current !== prevState.current
      || pageSize !== prevState.pageSize) {
      this.setFieldsValue();
      this.fetchRecoverList();
    }
  }

  // 设置表单值
  setFieldsValue = () => {
    const { formValues } = this.state;
    const { form } = this.props;

    form.setFieldsValue(formValues);
  }

  // 获取物流中心列表
  fetchLogisList = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'common/fetchLogisList',
    });
  }

  // 获取快递公司列表
  fetchExpressList = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'common/fetchExpressList2',
    });
  }

  // 获取数据
  fetchRecoverList = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'logisCenterDeliveryRecoverList/fetch',
      payload: this.getQueryParams(),
    });
  }

  // 获取查询参数
  getQueryParams = () => {
    const { formValues, current, pageSize } = this.state;
    const params = { ...formValues };
    params.pageNum = current;
    params.numPerPage = pageSize;

    return params;
  };

  /**
   * 查询
   */
  handleSearch = (e: React.FormEvent) => {
    e.preventDefault();

    const { form: { validateFields } } = this.props;
    validateFields((err, fieldsValue) => {
      if (err) return;

      const { start_end_time } = fieldsValue;

      if (start_end_time) {
        if (start_end_time[0]) {
          fieldsValue.startDateTime = moment(start_end_time[0]).format('YYYY-MM-DD HH:mm:ss');
        } else {
          fieldsValue.startDateTime = '';
        }

        if (start_end_time[1]) {
          fieldsValue.endDateTime = moment(start_end_time[1]).format('YYYY-MM-DD HH:mm:ss');
        } else {
          fieldsValue.endDateTime = '';
        }
      } else {
        fieldsValue.startDateTime = '';
        fieldsValue.endDateTime = '';
      }

      delete fieldsValue.start_end_time;

      const query = { page: 1, ...fieldsValue };
      const { dispatch } = this.props;
      addTab(dispatch, {
        name: '追回件管理',
        url: `${pathname}?${qs.stringify(query)}`,
        isTopMenu: true,
      });
    });
  };

  /**
   * 重置
   */
  handleReset = () => {
    const { form: { resetFields } } = this.props;
    resetFields();

    const { dispatch } = this.props;
    addTab(dispatch, {
      name: '追回件管理',
      url: pathname,
      isTopMenu: true,
    });
  };

  /**
   * 打开添加弹窗
   */
  handleOpenAddDialog = () => this.setState({ recoverDialog: true });

  /**
   * 打开编辑弹窗
   */
  handleOpenEditDialog = (orderInfo: any) => this.setState({ orderInfo, recoverDialog: true });

  /**
   * 关闭添加或编辑弹窗
   */
  handleCloseAddOrEdit = () => this.setState({ orderInfo: {}, recoverDialog: false });

  /**
   * 删除数据
   */
  handleDel = (info: any) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'logisCenterDeliveryRecoverList/del',
      payload: {
        query: this.getQueryParams(),
        params: { id: info.id },
      },
    });
  };

  /**
   * 确定添加或编辑
   */
  handleAddOrEdit = () => {
    const { orderInfo } = this.state;

    if (!orderInfo.expCode.trim()) {
      message.error('运单号不能为空');
      return;
    }

    if (!orderInfo.logisId) {
      message.error('请选择物流中心');
      return;
    }

    if (!orderInfo.expressId) {
      message.error('请选择快递公司');
      return;
    }

    // if (!orderInfo.phone.trim()) {
    //   message.error('请输入联系方式');
    //   return;
    // }

    // 不需要此字段了,默认写成0000
    orderInfo.phone = '0000';

    this.handleCloseAddOrEdit();

    let method = 'add';
    let params = orderInfo;
    if (orderInfo.id) {
      method = 'edit';
      params = _.pick(orderInfo, ['id', 'logisId', 'expressId', 'expCode', 'phone', 'remark']);
    }

    const { dispatch } = this.props;
    dispatch({
      type: `logisCenterDeliveryRecoverList/${method}`,
      payload: {
        query: this.getQueryParams(),
        params,
      },
    });
  };

  // 分页
  onSelectChange = (current: number, pageSize: number | undefined) => {
    const { formValues } = this.state;
    const query = {
      ...formValues,
      page: current,
      psize: pageSize,
    };

    const { dispatch } = this.props;
    addTab(dispatch, {
      name: '追回件管理',
      url: `${pathname}?${qs.stringify(query)}`,
      isTopMenu: true,
    });
  };

  /**
   * 输入运单号
   */
  handleChangeExpCode = (e: any) => this.changeExportInfo('expCode', e.target.value);

  /**
   * 选择物流中心
   */
  handleChangeLogis = (value: string) => this.changeExportInfo('logisId', value);

  /**
   * 选择快递公司
   */
  handleChangeExpress = (value: string) => this.changeExportInfo('expressId', value);

  /**
   * 输入新手机号
   */
  handleChangePhone = (e: any) => this.changeExportInfo('phone', e.target.value);

  /**
   * 输入备注
   */
  handleChangeRemark = (e: any) => this.changeExportInfo('remark', e.target.value);

  changeExportInfo = (key:string, value:any) => {
    const { orderInfo } = this.state;
    orderInfo[key] = value;
    this.setState({ orderInfo });
  }

  onClickRow = ({ id }: any) => ({
    onClick: () => {
      this.setState({ rowId: id });
    },
  })

  setRowClassName = ({ id }: any) => {
    const { rowId } = this.state;
    return id === rowId ? 'clickRowStyl' : '';
  }

  // 渲染查询表单
  renderSearchFormElem = () => {
    const {
      form: { getFieldDecorator },
      INITINFO: { expressList, logisList },
    } = this.props;

    return (
      <Form onSubmit={this.handleSearch} className="tableListForm">
        <Row gutter={12}>
        <Col md={8} sm={24}>
            <Item label="　起止时间" colon={false}>
              {getFieldDecorator('start_end_time', {
                initialValue: [moment(moment().subtract(2, 'days').format('YYYY-MM-DD 00:00:00')), ''],
              })(
                <RangePicker
                  showTime
                  placeholder={['开始时间', '截止时间']}
                  style={{ width: '100%' }}
                  format="YYYY/MM/DD HH:mm:ss"
                  disabledDate={current => timeLimit(current, 3)}
                  ranges={{
                    今天: [moment().startOf('day'), moment().endOf('day')],
                    本周: [moment().startOf('week'), moment().endOf('week')],
                    本月: [moment().startOf('month'), moment().endOf('month')],
                    上月: [
                      moment(moment().subtract({ day: new Date().getDate() - 1, month: 1 })),
                      moment(moment().subtract({ day: new Date().getDate(), month: 0 })),
                    ],
                  }}
                />,
              )}
            </Item>
          </Col>
          <Col md={4} sm={24}>
            <Item label="　运单号" colon={false}>
              {getFieldDecorator('expCode')(
                <Input placeholder="请输入" />,
              )}
            </Item>
          </Col>
          <Col md={4} sm={24}>
            <Item label="物流中心" colon={false}>
              {getFieldDecorator('logisId')(
                <Select
                  showSearch
                  allowClear
                  placeholder="请选择"
                  filterOption={(input: any, option: any) => (
                    option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                  )}
                >
                  {logisList.map((item: any) => (
                    <Option
                      value={String(item.id)}
                      key={item.id}
                    >{item.name}
                    </Option>
                  ))}
                </Select>,
              )}
            </Item>
          </Col>
          <Col md={4} sm={24}>
            <Item label="快递公司" colon={false}>
              {getFieldDecorator('expressId')(
                <Select
                  showSearch
                  allowClear
                  placeholder="请选择"
                  filterOption={(input: any, option: any) => (
                    option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                  )}
                >
                  {expressList.map((item: any) => (
                    <Option
                      value={String(item.id)}
                      key={item.id}
                    >{item.name}
                    </Option>
                  ))}
                </Select>,
              )}
            </Item>
          </Col>
          <Col md={4} sm={24}>
            <div className="flexFeView">
              <Button
                type="primary"
                htmlType="submit"
                className="smallButton"
              >
                查询
              </Button>
              <Button
                type="primary"
                className="addButton smallButton marginL16"
                onClick={this.handleReset}
              >
                重置
              </Button>
            </div>
          </Col>
        </Row>
      </Form>
    );
  }

  // 渲染追回件弹窗
  renderRecoverModalElem = () => {
    const { recoverDialog, orderInfo } = this.state;
    const { INITINFO: { expressList, logisList } } = this.props;
    const title = orderInfo.id ? '编辑追回件' : '添加追回件';

    return (
      <Modal
        title={title}
        visible={recoverDialog}
        onOk={this.handleAddOrEdit}
        onCancel={this.handleCloseAddOrEdit}
      >
        <Form className="tableListForm">
          <Row>
            <Col md={20} sm={20}>
              <Item label="　运单号" colon={false}>
                <Input
                  value={orderInfo.expCode}
                  onChange={this.handleChangeExpCode}
                />
              </Item>
            </Col>
          </Row>
          <Row>
            <Col md={20} sm={20}>
              <Item label="物流中心" colon={false}>
                <Select
                  showSearch
                  placeholder="请选择"
                  value={orderInfo.logisId}
                  onChange={this.handleChangeLogis}
                  filterOption={(input: any, option: any) => (
                    option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                  )}
                >
                  {logisList.reverse().map((item: any) => (
                    <Option value={item.id} key={item.id}>{item.name}</Option>
                  ))}
                </Select>
              </Item>
            </Col>
          </Row>
          {/* <Row>
            <Col md={20} sm={20}>
              <Item label="　联系人" colon={false}>
                <Input
                  type="number"
                  placeholder="请输入"
                  value={orderInfo.phone}
                  onChange={this.handleChangePhone}
                />
              </Item>
            </Col>
          </Row> */}
          <Row>
            <Col md={20} sm={20}>
              <Item label="快递公司" colon={false}>
                <Select
                  showSearch
                  placeholder="请选择"
                  value={orderInfo.expressId}
                  onChange={this.handleChangeExpress}
                  filterOption={(input: any, option: any) => (
                    option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                  )}
                >
                  {expressList.reverse().map((item: any) => (
                    <Option value={item.id} key={item.id}>{item.name}</Option>
                  ))}
                </Select>
              </Item>
            </Col>
          </Row>
          <Row>
            <Col md={20} sm={20}>
              <Item label="追回原因" colon={false}>
                <TextArea
                  rows={4}
                  value={orderInfo.remark}
                  onChange={this.handleChangeRemark}
                />
              </Item>
            </Col>
          </Row>
        </Form>
      </Modal>
    );
  }

  render() {
    const { current, pageSize } = this.state;
    const {
      logisCenterDeliveryRecoverList: { data },
      screen,
      loading,
    } = this.props;

    const pagination = data
      ? {
        total: data ? data.count : 0,
        pageSize,
        current: current || 1,
        onChange: this.onSelectChange,
        showTotal: () => `共${data.count || 0}条数据`,
        showQuickJumper: true,
        showSizeChanger: true,
        onShowSizeChange: this.onSelectChange,
      }
      : {};

    if (screen === 'sm' || screen === 'lg') {
      delete this.columns[this.columns.length - 1].fixed;
    } else if (screen === 'md') {
      this.columns[this.columns.length - 1].fixed = 'right';
    }

    return (
      <>
        <PageHeader />
        <Card bordered={false} className="searchForm">
          {this.renderSearchFormElem()}
        </Card>
        <Card bordered={false} className="tableList">
          <div className="tableBtns">
            <Button
              type="primary"
              size="small"
              className="addButton smallButton marginB12"
              onClick={this.handleOpenAddDialog}
            >
              添加
            </Button>
          </div>
          <Table
            rowKey="id"
            tableLayout="fixed"
            className="statementTable"
            columns={this.columns}
            dataSource={data.list || []}
            pagination={pagination}
            loading={loading}
            scroll={{ x: 1200 }}
            onRow={this.onClickRow}
            rowClassName={this.setRowClassName}
          />
        </Card>
        {this.renderRecoverModalElem()}
      </>
    );
  }
}

export default Form.create<TableListProps>()(TableList);
